// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = (event, context) => {
  const wxContext = cloud.getWXContext()

  return new Promise((resolve, reject) => {
    db.collection('workingGroup').doc(event.groupId).get()
      .then(res => {
        db.collection('groupMember').where({
            groupId: event.groupId,
            userId: wxContext.OPENID
          }).get()
          .then(res2 => {
            if (res2.data.length > 0) {
              resolve({})
            } else {
              db.collection('groupMember').add({
                  data: {
                    groupId: event.groupId,
                    userId: wxContext.OPENID
                  }
                })
                .then(res3 => {
                  resolve(res3)
                })
            }
          })
          .catch(e => {
            resolve({})
          })
      })


  })

}